import time
import logging
from .appman import AppWriter
from .config import Config

def check_intent(text):
    text = text.strip().strip(',.:：、，。')
    for line in Config.intents.splitlines():
        line = line.strip()
        if line:
            line = line.split('=', maxsplit=1)
            if len(line) == 2:
                prefix, intent = line
                for p in prefix.split(','):
                    if text.startswith(p):
                        return intent, text[len(p):].lstrip().lstrip(',.:：、，。')
    return None, text

class TextDispatcher:
    def __init__(self):
        self.intents = {k: AppWriter(**v) for k, v in Config.intent_targets.items()}
        self.active_intent = None
        self.last_intent = None
        self.last_intent_time = 0

    def input(self, text, finish):
        if not text:
            return
        intent, text = check_intent(text)
        if not intent:
            if time.time() - self.last_intent_time > Config.intent_memorize_time:
                self.last_intent = None
            if self.last_intent:
                intent = self.last_intent
        logging.info('intent={}, text=<{}>, finish={}'.format(intent, text, finish))
        if intent and intent in self.intents:
            if self.active_intent and intent != self.active_intent:
                last_writer = self.intents[self.active_intent]
                last_writer.cancel()
            writer = self.intents[intent]
            writer.input(text, finish)
            self.active_intent = intent
        if finish:
            if self.active_intent:
                self.last_intent = self.active_intent
                self.last_intent_time = time.time()
            self.active_intent = None

if __name__ == '__main__':
    print(check_intent('搜索小彭老师'))
